package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.dao.CascadeFieldDao;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.model.CascadeFieldSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameterSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;

public class CascadeFieldDaoImpl extends JdbcBase  implements CascadeFieldDao{
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			CascadeFieldDaoImpl.class);
	
	public boolean delete(String formId) throws DaoException{
		String sql = "delete from dc_foreignKey_set where formid = ? ";
		UpdateOperator update = new UpdateOperator(); 
		update.setSql(sql);
		try{
			update.addParameter(new SqlParameter(SqlType.VARCHAR,formId));
			update.access();
		}catch(Exception e){
			logger.error("", e);
			throw new DaoException("删除表单ID为："+formId+"  主从表外键定义信息出错！");
		}
	
		int effectCount = update.getEffectCounts();
		if(effectCount >0) {
			return true;
		}else{
			return false;
		}
	
	}

//	public List getCascadeFields(String formId) throws DaoException{
//		logger.debug(Constants.INTOMETHOD + "getFormFields");
//		StringBuffer sqlStr = new StringBuffer();
//		sqlStr
//				.append(
//						"select subTbl_field,maintbl_field from dc_foreignKey_set where formid = ?");
//		Connection conn = null;
//    	QueryOperator query = new QueryOperator();
//    	List formFields = null;
//    	try{
//    		conn = this.getConnection();
//        	query.setSql(sqlStr.toString());
//    		query.addParameter(new SqlParameter(SqlType.VARCHAR,formId));
//    		query.setUseOnlyConnectionFlag(true);
//    		query.setPresentConnection(conn);
//    		
//    		query.access();
//    		formFields =  new ArrayList();
//    		if(query.resultSetAvailable()){
//				//获取并处理记录集
//				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
//				for(int i=0;i<rs.rowCount;i++){					
//					CascadeFieldSet field = new CascadeFieldSet();
//					field.setMaintblField(rs.getFieldValueAsString("maintbl_field"));
//					field.setSubTblField(rs.getFieldValueAsString("subTbl_field"));
//					field.setValueSrc("主表当前记录");
//					
//					formFields.add(field);
//					rs.next();
//				}
//				rs.clearAll();
//			}
//    		
//    	}catch(Exception e){
//    		logger.error("", e);
//    		throw new DaoException("getCascadeFields throw error!");
//    	}finally{
//    		DBUtils.close(conn);
//    	}
//
//		return formFields;
//	}
	
	public List getCascadeFields(String formId) throws DaoException {
		String sql = "select id,subTbl_field,maintbl_field,formid,maint_field_type,sub_field_type from dc_foreignKey_set where formid=?";
		QueryOperator query = new QueryOperator();
		query.setSql(sql);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, formId));
		List keies = null;

		try {
			keies = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					CascadeFieldSet f = new CascadeFieldSet();
					f.setId(rs.getFieldValueAsString("id"));
					f.setSubTblField(rs.getFieldValueAsString("subTbl_field"));
					f.setMaintblField(rs.getFieldValueAsString("maintbl_field"));
					f.setValueSrc("主表当前记录");
					f.setFormId(rs.getFieldValueAsString("formId"));
					f.setMaintFieldType(rs.getFieldValueAsString("maint_field_type"));
					f.setSubFieldType(rs.getFieldValueAsString("sub_field_type"));

					keies.add(f);
					
					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("查找表单ID为：" + formId + " 对应的主从表外键关联字段名出错！");
		}
		return keies;
	}
	
	public boolean save(List formFields,String formId) throws DaoException{
		//先删除原有的信息
		this.delete(formId);
		
		StringBuffer sql = new StringBuffer();
		sql.append("insert into dc_foreignKey_set(id,subTbl_field,maintbl_field,formid,maint_field_type,sub_field_type)")
		   .append(" values(?,?,?,?,?,?)");
		
		Connection conn = null;
		UpdateOperator update = new UpdateOperator(); 
		update.setSql(sql.toString());

		try{
			conn = this.getConnection();
			update.setUseOnlyConnectionFlag(true);
			update.setPresentConnection(conn);
		
			for(Iterator iter = formFields.iterator();iter.hasNext();) {
				CascadeFieldSet cfs = (CascadeFieldSet)iter.next();
				SqlParameterSet spSet = new SqlParameterSet();
				
				String id = String.valueOf(this.getSeq("dc_foreignKey_set"));
				spSet.addParameter(new SqlParameter(SqlType.VARCHAR,id));
				spSet.addParameter(new SqlParameter(SqlType.VARCHAR,cfs.getSubTblField()));
				spSet.addParameter(new SqlParameter(SqlType.VARCHAR,cfs.getMaintblField()));
				spSet.addParameter(new SqlParameter(SqlType.VARCHAR,formId));
				spSet.addParameter(new SqlParameter(SqlType.VARCHAR,cfs.getMaintFieldType()));
				spSet.addParameter(new SqlParameter(SqlType.VARCHAR,cfs.getSubFieldType()));
				
				update.addBatchParameter(spSet);
			}
			update.access();

		}catch(Exception e){
			logger.error("", e);
			throw new DaoException("保存表单ID为："+formId+" 的主从表外键定义信息出错！");
		}finally{
			DBUtils.close(conn);
		}
		int effect[] = update.getBatchEffectCounts();
		if(effect.length>0) {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "表单ID为："+formId+" 的主从表外键定义信息"
						+ Constants.SUCCESS);
			}
			return true;
		}else{
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "表单ID为："+formId+" 的主从表外键定义信息"
						+ Constants.FAIL);
			}
			return false;
		}

	}
    
   
}
